#-*- coding:utf-8 -*-
'''
Created on 2012-11-26

@author: Binger
'''
from django.shortcuts import render_to_response
from django.contrib.auth.forms import UserCreationForm
from django.http import HttpResponseRedirect
from django.contrib import auth
from problem.models import Relation as pro_relation
from tutsau.models import Relation as tut_relation
from relax.models import Relation as rel_relation
from datetime import datetime
from news.models import news
from problem.models import Problem
from relax.models import Relax
from tutsau.models import Tutsau
from userinfo.models import Userinfo
from Graduation_web.settings import HOME_ITEM_LINES,NEW_USER_TITLE,NEW_USER_BODY
from django.contrib.auth.models import User
from message.models import Message
from django.contrib.auth.decorators import login_required
from _threading_local import local

def home_action(request):
    sign = 'home'
    linenum = HOME_ITEM_LINES
    username = request.session.get('user','')
    msg_count = get_msg_count(username)
    new = news.objects.all()[:23]
    problems = Problem.objects.all()[:linenum]
    relaxs = Relax.objects.all()[:linenum]
    tutsaus = Tutsau.objects.all()[:linenum]
    return render_to_response("home.html",locals())

def regiest_action(request):
    if request.method == "POST":
        user = UserCreationForm(request.POST)
        if user.is_valid():
            username = user.data['username']
            user.save()
            userinfo = Userinfo(username=user.data['username'],activity='0',id=User.objects.get(username = username))
            userinfo.save()
            user = auth.authenticate(username = username,password = user.data['password1'])
            auth.login(request,user)
            request.session['user'] = username
            user_from = Userinfo.objects.get(username = 'admin')
            user_to = Userinfo.objects.get(username = username)
            message = Message(title  = NEW_USER_TITLE,body = NEW_USER_BODY,state = 0,date = datetime.now(),user_from = user_from,user_to = user_to)
            message.save()
            return HttpResponseRedirect('/userinfo')  #成功
        else:
            error = '出错了，用户名已存在或两次密码输入不一致！'
            form = UserCreationForm()
            return render_to_response('regiest.html',locals())
    else:
        form = UserCreationForm()
        return render_to_response('regiest.html',locals())

def login_action(request):
    if request.method == 'POST':
        m_username = request.POST.get("username","")
        passwd = request.POST.get("passwd","")
        next = request.POST.get('next','')
        user = auth.authenticate(username = m_username,password = passwd)
        if not user:
            if next != '':
                error = "用户名或密码错误"
                return render_to_response("login_required.html",locals())
            return render_to_response("logerr.html",locals())
        auth.login(request,user)
        request.session['user'] = m_username
        username = m_username
        msg_count = get_msg_count(username)
        if next != '':
            if next.startswith('/submitwords'):
                next = '%s%s' % ('/',next[13:])
            return HttpResponseRedirect(next)
        return render_to_response("logined.html",locals())
    
    else:
        next = request.GET.get('next','')
        return render_to_response("login_required.html",locals())

def logout_action(request):
    auth.logout(request);
    request.session['user'] = 0
    return render_to_response("logout.html",locals())

@login_required
def submit_words_action(request):
    if request.method == "POST":
        username = request.session.get('user','')
        msg_count = get_msg_count(username)
        user_instance = Userinfo.objects.get(username = username)
        url = request.POST.get('type','')
        title_id = request.POST.get('title_id','')
        t_text = request.POST.get('text','')
        if url == 'singleproblem':
            title_instance = Problem.objects.get(id = title_id)
            relation = pro_relation(username = user_instance,title = title_instance,text = t_text,date = datetime.now())
            relation.save()
        elif url == 'singletutsau':
            title_instance = Tutsau.objects.get(id = title_id)
            relation = tut_relation(username = user_instance,title = title_instance,text = t_text,date = datetime.now())
            relation.save()
        elif url == 'singlerelax' :
            title_instance = Relax.objects.get(id = title_id)
            relation = rel_relation(username = user_instance,title = title_instance,text = t_text,date = datetime.now())
            relation.save()
    return HttpResponseRedirect('/'+url+'?id='+title_id+"&tolow=1&page=99999")

@login_required
def change_password_action(request):
    username = request.session.get('user','')
    msg_count = get_msg_count(username)
    userinfo = Userinfo.objects.get(username=username)
    activity = userinfo.activity
    if request.method == "POST":
        original_passwd = request.POST.get('original_passwd','')
        passwd1 = request.POST.get('passwd1','')
        passwd2 = request.POST.get('passwd2','')
        if passwd1 == passwd2:
            user = auth.authenticate(username = username,password = original_passwd)
            if user:
                user = User.objects.get(username = username)
                user.set_password(passwd1)
                user.save()
                success_msg = '密码修改成功！'
                return render_to_response('success.html',locals())
            else:
                error = '原密码错误！'
                return render_to_response('changepasswd.html',locals())
        else:
            error = '两次新密码不同！'
            return render_to_response('changepasswd.html',locals())
    else:
        return render_to_response('changepasswd.html',locals())
    
def get_msg_count(username):
    if username == 0 or username == '':
        return 0
    user = Userinfo.objects.get(username = username)
    return Message.objects.filter(user_to = user,state = 0).count()

def test_action(request):
    return render_to_response('test.html',locals())

def road_action(request):
    return render_to_response('road.html',locals())